package com.aurora.gulimall.member.service.impl;

import com.aurora.gulimall.member.dao.MemberLevelDao;
import com.aurora.gulimall.member.entity.MemberLevelEntity;
import com.aurora.gulimall.member.exception.PhoneExistException;
import com.aurora.gulimall.member.exception.UsernameExistException;
import com.aurora.gulimall.member.vo.MemberLoginVo;
import com.aurora.gulimall.member.vo.MemberRegistVo;
import com.aurora.gulimall.member.vo.SocialUser;
import com.aurora.gulimall.member.vo.SocialUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aurora.common.utils.PageUtils;
import com.aurora.common.utils.Query;

import com.aurora.gulimall.member.dao.MemberDao;
import com.aurora.gulimall.member.entity.MemberEntity;
import com.aurora.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //1、设置默认等级
        MemberLevelEntity memberLevel = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevel.getId());
        //检查用户名和手机号是否唯一。为了让controller感知异常，应使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setNickname(vo.getUsername());
        //密码应进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
//        boolean matches = passwordEncoder.matches(vo.getPassword(), encode);
        memberEntity.setPassword(encode);
        MemberDao baseMapper = this.baseMapper;
        baseMapper.insert(memberEntity);
    }

    /**检查手机号是否重复
     * @param phone
     * @throws PhoneExistException
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao baseMapper1 = this.baseMapper;
        Integer mobile = baseMapper1.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile > 0){
            throw new PhoneExistException();
        }

    }

    /**
     * 检查用户名是否重复
     * @param username
     * @throws UsernameExistException
     */
    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        MemberDao baseMapper1 = this.baseMapper;
        Integer mobile = baseMapper1.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(mobile > 0){
            throw new UsernameExistException();
        }
    }

    /**
     * 用户登录
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1、去数据库查询
        MemberDao baseMapper1 = this.baseMapper;
        MemberEntity memberEntity = baseMapper1.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or()
                .eq("mobile", loginacct));
        if (memberEntity == null){
            return null;
        }else{
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, memberEntity.getPassword());
            if(matches){
                return memberEntity;
            }else{
                return null;
            }
        }
    }

    /**社交账号登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity socialLogin(SocialUser vo) {
        //具有登录、注册两个逻辑
        int id = vo.getSocialUserInfo().getId();
        //1、判断当前用户是否已经登录过系统
        MemberDao socialDao = this.baseMapper;
        MemberEntity memberEntity = socialDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", id));
        if(memberEntity != null){
            //用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in()+"");
            socialDao.updateById(update);
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in()+"");
            return memberEntity;
        }else{
            //用户未注册
           MemberEntity member = new MemberEntity();
           member.setNickname(vo.getSocialUserInfo().getName());
           member.setSocialUid(String.valueOf(vo.getSocialUserInfo().getId()));
           member.setExpiresIn(String.valueOf(vo.getExpires_in()));
           socialDao.insert(member);
           return member;
        }
    }

}